<template>
  <div class="app-container">
    <el-collapse v-model="active_names" @change="handleChange">

      <el-collapse-item name="1">
        <template slot="title">
          <span class="collapse-itemtitle">基本信息</span>
          <!-- <div class="btn-save">
            <el-button type="primary">编辑</el-button>
          </div> -->
        </template>
        <div class="row-form-container">
          <row-form left_title="账号身份" right_title="企业身份">
            <span slot="left_content">{{ temp1.account_identity }}</span>
            <span slot="right_content">{{ temp1.corporation_identity }}</span>
          </row-form>
          <row-form left_title="账 号 ID" right_title="注册时间">
            <span slot="left_content">{{ 'temp1.id' }}</span>
            <!-- <template slot="right_content">
              <el-date-picker v-model="temp1.data_time" type="datetime" placeholder="选择日期时间"></el-date-picker>
            </template> -->
            <span slot="right_content"> {{ new Date() | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
          </row-form>
        </div>
      </el-collapse-item>

      <el-collapse-item name="2">
        <template slot="title">
          <span class="collapse-itemtitle">业务信息</span>
          <div class="btn-save">
            <el-button v-show="!temp2.is_edit" type="primary" @click.stop="temp2.is_edit = true">编辑</el-button>
            <el-button v-show="temp2.is_edit" type="primary" @click.stop="temp2.is_edit = false">保存</el-button>
            <el-button v-show="temp2.is_edit" type="danger" @click.stop="temp2.is_edit = false">取消</el-button>
          </div>
        </template>
        <div class="row-form-container">
          <row-form left_title="主要行业应用" right_title="主营业务" :left_require="false" :right_require="false">
            <!-- <span slot="left_content">{{'学校'}}</span> -->
            <template slot="left_content">
              <el-select
                v-model="temp2.industry"
                filterable
                reserve-keyword
                placeholder="请选择行业"
                style="width: 50%"
                clearable
                :disabled="!temp2.is_edit"
              >
                <el-option v-for="item in list_industry" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </template>

            <input slot="right_content" class="input-row-form" :value="temp2.scope" :disabled="!temp2.is_edit">
          </row-form>
          <row-form left_title="网址" :left_require="false" :right_require="false">
            <input slot="left_content" class="input-row-form" :value="temp2.url" :disabled="!temp2.is_edit">
          </row-form>
        </div>
      </el-collapse-item>

      <el-collapse-item name="3">
        <template slot="title">
          <span class="collapse-itemtitle">企业联系信息</span>
          <div class="btn-save">
            <el-button v-show="!temp3.is_edit" type="primary" @click.stop="temp3.is_edit = true">编辑</el-button>
            <el-button v-show="temp3.is_edit" type="primary" @click.stop="temp3.is_edit = false">保存</el-button>
            <el-button v-show="temp3.is_edit" type="danger" @click.stop="temp3.is_edit = false">取消</el-button>
          </div>
        </template>
        <div class="row-form-container">
          <row-form left_title="国家" right_title="所在地区">
            <span slot="left_content" :disabled="!temp3.is_edit">{{ '中国' }}</span>
            <span slot="right_content" :disabled="!temp3.is_edit">{{ '浙江省杭州市' }}</span>
          </row-form>
          <row-form left_title="街道地址" right_title="联系电话" :left_require="false" :right_require="false">
            <input slot="left_content" class="input-row-form" :value="temp3.street" :disabled="!temp3.is_edit">
            <input slot="right_content" class="input-row-form" :value="temp3.corporation_tel" :disabled="!temp3.is_edit">
          </row-form>
        </div>
      </el-collapse-item>

      <el-collapse-item name="4">
        <template slot="title">
          <span class="collapse-itemtitle">企业认证信息</span>
          <div class="btn-save">
            <el-button v-show="!temp4.is_edit" type="primary" @click.stop="temp4.is_edit = true">编辑</el-button>
            <el-button v-show="temp4.is_edit" type="primary" @click.stop="temp4.is_edit = false">保存</el-button>
            <el-button v-show="temp4.is_edit" type="danger" @click.stop="temp4.is_edit = false">取消</el-button>
          </div>
        </template>
        <div class="row-form-container">
          <row-form left_title="企业社会信用编码" right_title="企业营业执照">
            <input slot="left_content" class="input-row-form" :value="temp4.code" :disabled="!temp4.is_edit">
            <input slot="right_content" class="input-row-form" :value="temp4.certificate">
          </row-form>
        </div>
      </el-collapse-item>

      <el-collapse-item name="5">
        <template slot="title">
          <span class="collapse-itemtitle">安全设置</span>
          <div class="btn-save">
            <el-button v-show="!temp5.is_edit" type="primary" @click.stop="temp5.is_edit = true">编辑</el-button>
            <el-button v-show="temp5.is_edit" type="primary" @click.stop="temp5.is_edit = false">保存</el-button>
            <el-button v-show="temp5.is_edit" type="danger" @click.stop="temp5.is_edit = false">取消</el-button>
          </div>
        </template>
        <div class="row-form-container">
          <row-form left_title="登录密码" right_title="手机绑定" :left_require="false" :right_require="false">
            <div slot="left_content" class="row-content">
              <input ref="input_password" class="input-row-form2" type="password" :value="temp5.password" :disabled="!temp5.is_edit">
              <div class="action">
                <span style="color:#108CFD; cursor: pointer;">已设置</span>
                |
                <span style="color: #FF7275; cursor: pointer;" @click="editPassword">修改</span>
              </div>
            </div>
            <div slot="right_content" class="row-content">
              <!-- <input class="input-row-form2" disabled :value="temp5.tel"/> -->
              <span>{{ temp5.tel }}</span>
              <div class="action">
                <span style="color:#108CFD; cursor: pointer;">已设置</span>
              </div>
            </div>

          </row-form>
          <row-form left_title="备用邮箱" right_title="AccessKey" :left_require="false" :right_require="false">
            <div slot="left_content" class="row-content">
              <input ref="input_email" class="input-row-form2" :value="temp5.email" :disabled="!temp5.is_edit">
              <div class="action">
                <span style="color:#108CFD; cursor: pointer;">{{ temp5.email? '已设置':'未设置' }}</span>
                |
                <span style="color: #FF7275; cursor: pointer;" @click="setEmail">设置</span>
              </div>
            </div>

            <div slot="right_content" class="row-content">
              <input class="input-row-form2" :type="password_type_ak" :value="temp5.AKey" :disabled="true">
              <div class="action">
                <span style="color:#108CFD; cursor: pointer;" @click="showPwd(0)">
                  <svg-icon :icon-class="password_type_ak === 'password' ? 'eye' : 'eye-open'" />
                </span>
              </div>
            </div>
          </row-form>
          <row-form left_title="SecretKey" :left_require="false" :right_require="false">
            <div slot="left_content" class="row-content">
              <input class="input-row-form2" :type="password_type_sk" :value="temp5.SKey" :disabled="!temp5.is_edit">
              <div class="action">
                <span style="color: #FF7275; cursor: pointer;" @click="resetSK">重置</span>
                |
                <span style="color:#108CFD; cursor: pointer;" @click="showPwd(1)">
                  <svg-icon :icon-class="password_type_sk === 'password' ? 'eye' : 'eye-open'" />
                </span>
              </div>
            </div>
          </row-form>
        </div>
      </el-collapse-item>

    </el-collapse>

  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils' // 解析时间
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import RowForm from './components/RowForm'
import { delAdmin, addAdmin, editAdmin, listAdmin, toggleAdmin, listRole } from '@/api/system'
import { validPass } from '@/utils/validate'
import { logger } from 'runjs/lib/common'
const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]
// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'InfoBasics',
  components: { Pagination, RowForm },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    const validatePassword = (rule, value, callback) => {
      // if (!validPass(value) && (value && value.length != 64)) {
      if (!validPass(value)) {
        callback(new Error('8~16位,包含大小写字母和数字, 可以有特殊字符'))
      } else { callback() }
    }

    return {
      active_names: ['1', '2', '3', '4', '5'],
      listQuery: {
        page: 1, // 第几页
        limit: 10, // 每页显示的条数row
        keyword: '' // 搜索关键字
      },
      temp1: {
        account_identity: '合作企业',
        corporation_identity: '牛力智能科技有限公司',
        id: '549684509684509',
        data_time: new Date()
      },
      temp2: {
        is_edit: false,
        industry: '医院',
        url: 'www.newly-ai.cn',
        scope: '业务范围是1234567'
      },
      temp3: {
        is_edit: false,
        nationality: '中国',
        province_city: '',
        street: '地址是.........', // 街道地址
        corporation_tel: '15677779999' // 企业联系电话
      },
      temp4: {
        is_edit: false,
        code: '392854739345',
        certificate: '查看营业执照'
      },
      temp5: {
        is_edit: false,
        password: 'hsdjkweiushdi',
        tel: '13788998899', // 账号(绑定的手机号)
        email: '345345@new.ai',
        AKey: 'asdlkfkjsdl',
        SKey: 'ahsjdlfasdj'
      },
      list_industry: [{ name: '学校', id: 1 }, { name: '医院', id: 2 }, { name: '社区物业', id: 3 }], // 应用的行业类型列表
      password_type_ak: 'password',
      password_type_sk: 'password',

      multipleSelection: [],
      is_multip: false, // 是否批量删除
      tableKey: 0,
      list: null,
      total: 0, // 总条数
      listLoading: true,

      calendarTypeOptions,
      statusOptions: ['published', 'draft', 'deleted'], // 角色

      old_pass: '', // 原密码
      dialogFormVisible: false,
      dialogStatus: '',
      del_id: '',
      del_index: null,
      dialogPvVisible: false, // 删除提示框
      dialogToggle: false, // 状态更改的提示框
      rules: {
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        userName: [{ required: true, trigger: 'blur', validator: validatePassword }],
        again_pass: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      list_role: [], // 获取角色和角色id的 列表
      toggle_id: '', //
      toggle_status: '', // 要切换的状态值
      reg_tooltip: false, // 大写 ?
      reg2_tooltip: false, // 大写 ?
      status_index: '' // 在tab列表页面,, 要切换状态值的  下标,

    }
  },
  watch: {
    dialogFormVisible: {
      handler(val, oldval) {
        if (val) {
          this.getListRole() // 获得角色列表
        }
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 点击折叠
    handleChange(val) {
      console.log(val)
    },
    // 点击修改密码
    editPassword() {
      // this.$refs['input_password'].value = ''   // 清空原来密码
      this.$nextTick(() => { // 待Dom更新完毕 获取到输入框焦点
        this.$refs.input_password.focus()
      })
    },
    // 点击设置邮箱
    setEmail() {
      this.$nextTick(() => { // 待Dom更新完毕 获取到输入框焦点
        this.$refs.input_email.focus()
      })
    },
    // 重置SK
    resetSK() {
      console.log('点击了 重置SK')
    },

    // 获取 table 列表
    getList() {
      this.listLoading = true
      listAdmin(this.listQuery.page, this.listQuery.limit, this.listQuery.keyword).then(res => {
        this.list = res.data.records
        this.total = parseInt(res.data.total)

        setTimeout(() => {
          this.listLoading = false
        }, 1 * 1000)
      })
    },
    // 点击了 状态值切换
    changeStatus(id, status, index) {
      this.status_index = index
      this.toggle_id = id
      this.toggle_status = status
      this.dialogToggle = true
    },
    // 确认了  状态值切换
    toggleStatus() {
      toggleAdmin(this.toggle_id, this.toggle_status).then(res => {
        this.$notify({
          title: '成功',
          message: '状态修改成功',
          type: 'success',
          duration: 4000
        })
        // this.$message({
        //   message: "状态更改成功!",
        //   type: 'success',
        //   duration: 4000,
        //   showClose: true,
        //   center: true,
        // })
        this.getList() // 重新渲染页面
        this.dialogToggle = false
      })
    },
    // 获取角色列表
    getListRole() {
      listRole(1, 49, '').then(res => {
        this.list_role = res.data.records
      })
    },
    // 监听是否打开了大写
    checkCapslock(num, e) {
      const { key } = e
      if (num == 0) { // 注册账号: 设置密码
        this.reg_tooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z') // 若开启大写则提示文字
      } else if (num == 1) { // 注册账号: 再次输入密码
        this.reg2_tooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z') // 若开启大写则提示文字
      }
    },
    // 是否显示密码
    showPwd(num) {
      if (num == 0) {
        this.password_type_ak === 'password' ? this.password_type_ak = '' : this.password_type_ak = 'password'
        // this.$nextTick(() => { // 待Dom更新完毕 获取到输入框焦点
        //   this.$refs.password_reg.focus()
        // })
      } else if (num == 1) {
        this.password_type_sk === 'password' ? this.password_type_sk = '' : this.password_type_sk = 'password'
        // this.$nextTick(() => { // 待Dom更新完毕 获取到输入框焦点
        //   this.$refs.password_reg2.focus()
        // })
      }
    },
    // 取消状态管理
    handleCancel() {
      this.getList() // 重新渲染页面
      this.dialogToggle = false
    },
    // 点击了 '编辑' 或添加======================================================
    handleUpdate(row, str) {
      if (str == 'create') this.resetTemp() // 清空
      if (str == 'update') {
        this.temp = Object.assign({}, row) // 克隆一个对象
        this.old_pass = this.temp.password
        this.temp.password = '' // 不回显密码
      }
      this.dialogStatus = str

      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 编辑: 确认更新数据
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // if(this.temp.password == this.old_pass){   // 修改了但是没改密码
          //   editAdmin(this.temp.id, '', this.temp.roleId, this.temp.status, this.temp.userName).then(() => {
          //     // const index = this.list.findIndex(v => v.id === this.temp.id) // 找到被更改的item下标
          //     // this.list.splice(index, 1, this.temp) // 通过下标更改list的数据
          //     this.getList()
          //     this.dialogFormVisible = false
          //     this.$notify({
          //       title: '成功',
          //       message: '更新成功',
          //       type: 'success',
          //       duration: 4000
          //     })
          //   })
          // }
          if (this.temp.password == this.temp.again_pass) { // 修改的内容包括: 密码
            const cryptograph = this.$sha256(this.temp.password + this.temp.userName)
            editAdmin(this.temp.id, cryptograph, this.temp.roleId, this.temp.status, this.temp.userName).then(() => {
              // const index = this.list.findIndex(v => v.id === this.temp.id) // 找到被更改的item下标
              // this.list.splice(index, 1, this.temp) // 通过下标更改list的数据
              this.getList()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 4000
              })
            })
          } else {
            this.$message({
              message: '两次密码输入不一致!',
              type: 'error',
              duration: 4000,
              showClose: true,
              center: true
            })
          }
        }
      })
    },
    // 确认添加了一个管理员
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.temp.password != this.temp.again_pass) {
            this.$message({
              message: '两次密码输入不一致!',
              type: 'error',
              duration: 4000,
              showClose: true,
              center: true
            })
          } else {
            const cryptograph = this.$sha256(this.temp.password + this.temp.userName)
            // let data2 = Object.assign({}, this.temp)   // 克隆一个对象

            addAdmin(cryptograph, this.temp.roleId, 1, this.temp.userName).then(() => {
              // this.list.unshift(this.temp)
              this.getList()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 4000
              })
            })
          }
        }
      })
    },
    // 清空temp
    resetTemp() {
      this.temp = {
        id: undefined,
        userName: '',
        password: '',
        again_pass: '',
        status: 1,
        role: ''
      }
    },
    // 点击了删除===============================================
    handleDelete(row, index) {
      this.is_multip = false
      this.del_id = row.id
      this.del_index = index
      this.dialogPvVisible = true
    },
    // 点击了 批量删除
    handleDelmultip() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: '没有被选项!',
          type: 'error',
          duration: 4000,
          showClose: true,
          center: true
        })
      } else {
        this.is_multip = true
        this.dialogPvVisible = true
      }
    },
    // 确认了删除
    delData() {
      let ids = []
      if (this.is_multip) { // 批量删
        this.multipleSelection.forEach((item, i) => {
          ids.push(item.id)
        })
        // ids = this.multipleSelection
      } else {
        ids = [this.del_id]
      }
      delAdmin(ids).then(() => {
        this.dialogPvVisible = false
        // this.list.splice(this.del_index, 1)
        this.getList()
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 4000
        })
      })
    },

    // 搜索
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 批量选择
    handleSelectionChange(val) {
      this.multipleSelection = val
    }
  }
}
</script>

<style lang="scss" >
  @import "~@/styles/variables.scss";

  .app-container {
    // position: relative;
    .el-collapse {
      .el-collapse-item {
        position: relative;
        .el-collapse-item__content {
          padding-bottom: 0 !important;
        }
        // .btn-save {
        //   position: absolute;
        //   right: 40px;
        //   top: 0;
        // }
        // .collapse-itemtitle {
        //   text-indent: 10px;
        //   font-weight: 800;
        //   font-size: 18px;
        // }
        // .row-form-container {
        //   border-left: 1px solid $border_middle;
        //   border-bottom: 1px solid $border_middle;
        // }
        // .input-row-form {
        //   width: 80%;
        //   border: 0;
        // }
        // .input-row-form2 {
        //   width: 70%;
        //   border: 0;
        //   height: 40px;
        // }
        // .row-content {
        //   display: flex;
        //   justify-content: space-between;
        //   align-items: center ;
        //   // background-color: aqua;
        // }
        // .row-content span:hover {
        //   text-decoration: underline;
        // }
      }

    }

  }
</style>

<style lang="scss" scoped>
  @import "~@/styles/variables.scss";

  .app-container {
    // background-color: #f99 !important;
    .el-collapse {

      .el-collapse-item {
        .btn-save {
          position: absolute;
          right: 40px;
          top: 0;
        }
        .collapse-itemtitle {
          text-indent: 10px;
          font-weight: 800;
          font-size: 18px;
        }
        .row-form-container {
          border-left: 1px solid $border_middle;
          border-bottom: 1px solid $border_middle;
        }
        .input-row-form {
          width: 80%;
          border: 0;
        }
        .input-row-form2 {
          width: 70%;
          border: 0;
          height: 40px;
        }
        .row-content {
          display: flex;
          justify-content: space-between;
          align-items: center ;
          // background-color: aqua;
        }
        .row-content .action span:hover {
          text-decoration: underline;
        }
      }
    }

  }
</style>
